#include "VoltageSensor.h"

#include "../stm32/stm32f10x.h"
#include "ADConvert.h"
#include "VBattery.h"

struct _VoltageSensor
{
        ADChannelType base_type;
#ifdef VBATTERY_H
        VBattery *vbattery;
#endif
};

static VoltageSensor global_voltage_sensor;

static float         voltage_adjust = 0.0f;

VoltageSensor *
voltage_sensor_new_from_global(void)
{
        adconvert_init();
        global_voltage_sensor.base_type = ADCHANNEL_TYPE_VOLTAGE;

        /* 自动校准 */
        const uint16_t _voltage =
                adconvert_get_value_once(ADCHANNEL_TYPE_VOLTAGE);
        voltage_adjust = (float)_voltage * 0.004029304f;
#ifdef VBATTERY_H
        global_voltage_sensor.vbattery = vbattery_new_from_global();
#endif
        return &global_voltage_sensor;
}

float
voltage_sensor_get_voltage(const VoltageSensor *self)
{
#ifndef VBATTERY_H
        return 0.004029304f * (float)adconvert_get_value_once(self->base_type) -
               voltage_adjust;
#else
        return vbattery_get_charge_voltage(self->vbattery);
#endif
}
